package system.service;

import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import core.exception.FormulaAnalysisException;
import core.toolbox.formulaAnalysis.FormulaAnalysis;
import system.dao.AccountSubjectDao;
import system.dao.ReportDao;

import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2017/3/13.
 */
public class FormulaService {
    AccountSubjectDao jzpzDao = Duang.duang(AccountSubjectDao.class);
    ReportDao reportDao = Duang.duang(ReportDao.class);


    /**
     * 插入公式
     * @param record
     * @return
     */
    public boolean insert(Record record) {
        String reportName = record.getStr("reportName");
        String projectName = record.getStr("projectName");
        String projectType = record.getStr("projectType");
        String formula = record.getStr("formula");
        return insert(reportName, projectName, projectType, formula);
    }

    /**
     * 插入公式
     * @param reportName 报表名称
     * @param projectName 项目名称
     * @param projectType 项目类型
     * @param formula 计算公式
     * @throws FormulaAnalysisException
     */
    public boolean insert(String reportName,String projectName,String projectType, String formula) throws FormulaAnalysisException {
        //////获取reportid///////
        Integer reportid = reportDao.getReportidByName(reportName);
        //////获取formulaid//////
        String formulaid = UUID.randomUUID().toString().replace("-","");
        //////封装reportinfo//////
        final Record reportinfo = new Record();
        reportinfo.set("reportid", reportid);
        reportinfo.set("projectname", projectName);
        reportinfo.set("projecttype", projectType);
        reportinfo.set("formulaid", formulaid);
        //////封装formula////////
        final List<Record> formulaList = FormulaAnalysis.analysisString(formula,formulaid);
        ////开启事务///////
        boolean isSuccess = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                boolean a = Db.save("reportinfo", reportinfo);
                int[] formulas = Db.batchSave("formula", formulaList, 100);
                int b = 0;
                for(int i : formulas) b+=i;
                return a&&b==formulaList.size();
            }
        });
        return isSuccess;
    }
}
